import {UploadOutlined} from "@ant-design/icons";
import {request} from "@umijs/max";
import {UploadProps, Upload, Button} from "antd";
import {forwardRef, useEffect, useImperativeHandle, useState} from "react";

export async function upload(
  data: FormData,
  options?: { [key: string]: any },
) {
  return request<{
    code: number;
    data: Record<string, any>;
    msg?: string;
  }>('/product-server/api/v1/file/upload', {
    method: 'POST',
    data,
    ...(options || {}),
  });
}

const CustomFileUpload = (props: any, ref: any) => {
  const [fileList, setFileList] = useState<any[]>([])

  useEffect(() => {
    if (Array.isArray(props.value)) {
      setFileList(props.value || [])
    }
  }, [props.value])

  const defaultProps: UploadProps = {
    maxCount: 1,
    fileList: Array.isArray(props.value) ? props.value : [],
    onRemove(file) {
      // console.log('file', file);
      const newFileList = fileList?.filter((item: any) => item?.uid !== file.uid)
      setFileList([...newFileList])
    },
    customRequest: async (file) => {
      // console.log('file', file);
      props?.onUploadStart?.()
      try {
        const formData = new FormData()
        formData.append("file", file.file)
        formData.append("type", props.type || 'product')
        const res = await upload(formData)
        // console.log(res);
        props?.onUploadSuccess?.(res)
        // console.log('props.value', props.value);

        const copyFileList = (props.value || [])?.map((item: any) => {
          if ((file.file as any)?.uid === item?.uid) {
            item.status = 'done'
            item.uid = (file?.file as any)?.uid
            item.name = (file?.file as any)?.name
            item.url = res?.data?.url
            item.size = res?.data?.size
          }
          return item
        })
        // console.log('copyFileList', copyFileList);
        setFileList([...copyFileList])
        props?.onChange?.([...copyFileList])
        // console.log(fileKeyMapRef, props.fieldKey, newFileList);
      } catch (e) {
        // setLoading(false)
        props?.onUploadFail?.()
      }
    }
  };

  useImperativeHandle(ref, () => ({}))

  return <Upload {...defaultProps} {...props} onChange={({fileList}) => {
    props?.onChange?.(fileList)
  }}>
    {props.children ? props.children : <Button icon={<UploadOutlined/>}>上传文件</Button>}
  </Upload>
}


export default forwardRef(CustomFileUpload)
